package com.kunbo.cn.service.impl.core.purchase;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.kunbo.cn.service.core.purchase.PurchaseOrderService;
import com.kunbo.cn.util.date.CommonsUtil;

@Service
public class PurchaseOrderImpl implements PurchaseOrderService{
	
	
	@Autowired
	private JdbcTemplate jdbc;
	
	

	@Override
	public List<Map<String, Object>> selOrder(String startTime, String endTime, String orderCode, String material,
			Integer placeoftransportation,Integer page, Integer pageSize) {
		// TODO Auto-generated method stub
		String supplier = "select name from business_supplier_manage where id = " + placeoftransportation;
		Map<String,Object> supplierMap = jdbc.queryForMap(supplier);
		String supplierName = "";
		if(supplierMap.size() > 0 ) {
			supplierName = supplierMap.get("name").toString();
		}
		String sql = "select purchase_waybill_placeoftransportation,purchasing_unit,purchase_order_code,purchase_order_name,material_name,unit_price,number_of_contracts,order_amount,actual_quantity,adjustment_amount,allowance,purchase_order_time from bussiness_purchasing_order_manager where 1 = 1 and purchase_waybill_placeoftransportation = '" + supplierName + "'";
		String sqlCount = "select count(id) as `count` from bussiness_purchasing_order_manager where 1 = 1 and purchase_waybill_placeoftransportation = '" + supplierName + "'";
		if(startTime!= null && !startTime.isEmpty()) {
			sqlCount += " and purchase_order_time > '" + startTime +"'";
			sql += " and purchase_order_time > '" + startTime +"'";
		}
		if(endTime != null && !endTime.isEmpty()) {
			Long cTime= CommonsUtil.stringToTime(endTime)+86400000L;//时间加1天
			 String end=CommonsUtil.timeToString(cTime);
			sqlCount += " and purchase_order_time < '" + end + "'";
			sql += " and purchase_order_time < '" + end + "'";
		}
		if(orderCode != null && !orderCode .isEmpty()) {
			sqlCount += " and purchase_order_code like '%" + orderCode + "%'";
			sql += " and purchase_order_code like '%" + orderCode + "%'";
		}
		if(material != null && !material .isEmpty()) {
			sqlCount += " and material_name like '%" + material +"%'";
			sql += " and material_name like '%" + material +"%'";
		}
		System.out.println(sql);
		sql += " order by id desc limit " + (page*pageSize) + "," + pageSize;
		System.out.println(sql);
		int count = Integer.parseInt(jdbc.queryForMap(sqlCount).get("count").toString());
		List<Map<String, Object>> list = jdbc.queryForList(sql);
		if(list.size() > 0) {
			list.get(0).put("count", count);
		}
		return list;
	}

}
